<!-- 整改巡检单纪录 -->
<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="工程名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入工程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['quality:form:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >创建整改通知单</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['quality:form:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="formList">
      <el-table-column label="巡检单标题" align="center" show-overflow-tooltip prop="formTitle" />
      <el-table-column label="检查描述" align="center" show-overflow-tooltip prop="formDes" />
      <el-table-column label="项目名称" align="center" show-overflow-tooltip prop="projectNameBase" />
      <el-table-column label="工程名称" align="center" show-overflow-tooltip prop="projectName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['quality:form:edit']"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleExport(scope.row.id)"
          >导出巡检单</el-button>
          <el-button
            v-hasPermi="['quality:form:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-hasPermi="['quality:form:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改整改巡检单记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form
        ref="form"
        v-loading="formLoading"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="巡检单标题" prop="formTitle">
              <el-input v-model="form.formTitle" placeholder="请输入巡检单标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工程名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入工程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="整改期限" prop="rectificationDeadline">
              <el-input v-model="form.rectificationDeadline" placeholder="请输入" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检查描述" prop="formDes">
              <el-input v-model="form.formDes" type="textarea" :rows="3" placeholder="请输入检查描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="整改要求" prop="rectificationRequirementsList">
              <div>
                <div
                  v-for="(tag,index) in form.rectificationRequirementsList"
                  :key="tag"
                  class="txt-box"
                >
                  {{ index+1 }}、{{ tag }}
                  <i class="el-icon-close" @click="handleClose(tag)" />

                </div>
                <el-input
                  v-if="inputVisible"
                  ref="saveTagInput"
                  v-model="inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <div v-else>
                  <el-button class="button-new-tag" size="small" @click="showInput">新增</el-button>
                </div>

              </div>

            </el-form-item>
          </el-col>
        </el-row>
        <el-card class="box-card">
          <el-form :model="queryParamsDialog" size="small" :inline="true" label-width="70px" @submit.native.prevent>

            <el-form-item label="问题描述" prop="questionDesc">
              <el-input v-model="queryParamsDialog.questionDesc" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="queryParamsDialog.pageNum=1,getQualityProblemList()">搜索</el-button>
            </el-form-item>
          </el-form>
          <!-- 质量问题台账 -->
          <el-table
            v-if="showTable"
            ref="multipleTable"
            v-loading="formLoading"
            :data="list"
            row-key="id"
            @selection-change="selectionDialogFun"
          >
            <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
            <!-- <el-table-column label="id" align="center" show-overflow-tooltip width="120" prop="id" /> -->
            <el-table-column label="问题编号" align="center" show-overflow-tooltip width="120" prop="workNo" />
            <el-table-column label="问题整改状态" align="center" width="120" prop="dataStatus">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.list_quality_data_status"
                  :value="scope.row.dataStatus"
                />
              </template>
            </el-table-column>
            <el-table-column label="问题描述" align="center" show-overflow-tooltip width="120" prop="questionDesc" />
            <el-table-column label="数据来源" align="center" show-overflow-tooltip prop="dataSource" width="160">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.list_quality_data_source"
                  :value="scope.row.dataSource"
                />
              </template>
            </el-table-column>
            <el-table-column label="责任区域" align="center" width="120" prop="dutyAreaName" />
            <el-table-column label="检查人" align="center" width="120" prop="checkPeopleName" />
            <el-table-column label="整改人" align="center" width="120" prop="revisePeopleName" />
            <el-table-column label="复杳人" align="center" width="120" prop="reviewUserName" />
            <el-table-column label="通知人" align="center" width="120" prop="notifierName" />
            <el-table-column label="问题等级" align="center" width="120" prop="questionLevel">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.list_quality_level"
                  :value="scope.row.questionLevel"
                />
              </template>
            </el-table-column>
            <el-table-column label="整改完成时间" align="center" width="160" prop="reviewTime" />
            <el-table-column
              align="center"
              label="要求整改完成日期"
              width="140"
              prop="reviseTheDates"
            />
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="120"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="chooseImg(scope.row)"
                >选择图片</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="totalDialog > 0"
            :total="totalDialog"
            :page.sync="queryParamsDialog.pageNum"
            :limit.sync="queryParamsDialog.pageSize"
            @pagination="paginationFun"
          />
        </el-card>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择图片 -->
    <el-dialog title="选择图片" :visible.sync="imgDialog" width="70%" append-to-body>
      <div class="previewImg">
        <div v-for="item in imgList" :key="item.url" class="img-box">
          <el-image
            class="img"
            :src="item.url"
            fit="contain"
            :lazy="true"
            :preview-src-list="imgList.map(item => item.url)"
          />
          <el-checkbox v-model="item.checked" />
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseImgOkFun">确 定</el-button>
        <el-button @click="imgDialog=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listForm,
  getForm,
  delForm,
  addForm,
  updateForm,
  getDataList,
  getLastOne
} from '@/api/quality/form'
import { download1 } from '@/utils/request'
export default {
  dicts: ['list_quality_level', 'list_quality_data_status', 'list_quality_data_source'],
  name: 'Form',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 整改巡检单记录表格数据
      formList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null// 工程名称
      },
      // 表单参数
      form: {
        rectificationRequirementsList: []
      },
      // 表单校验
      rules: {
        formTitle: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        projectName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        rectificationDeadline: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        formDes: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        rectificationRequirementsList: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      // 质量问题台账
      list: [],
      totalDialog: 0,
      formLoading: false,
      // 查询参数
      queryParamsDialog: {
        pageNum: 1,
        pageSize: 10,
        projectId: this.$store.state.app.selectData,
        questionDesc: null
      },
      selectionList: [], // 选中的质量问题台账
      inputVisible: false,
      inputValue: '',
      // 选择图片
      imgDialog: false,
      chooseImgList: [], // 选择的图片
      imgList: [], // 渲染的图片列表,默认是全部选中状态
      baseMinioUrl: process.env.VUE_APP_MINIO_BASE_API,
      showTable: false,
      newItemList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 整改要求单条删除
    handleClose(tag) {
      this.form.rectificationRequirementsList.splice(this.form.rectificationRequirementsList.indexOf(tag), 1)
    },
    // 整改要求 新增按钮
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 失去焦点- 整改要求新增数据
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.form.rectificationRequirementsList.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 选择质量问题台账
    selectionDialogFun(val) {
      this.selectionList = val
    },
    // 选择图片
    chooseImg(row) {
      this.imgDialog = true
      this.imgList = []
      this.chooseImgList = []
      if (row.attachList?.length) {
        row.attachList.forEach(item => {
          item.url = this.baseMinioUrl + '/' + item.bucket + '/' + item.name
          this.imgList.push({ url: item.url, checked: item.checked })
        })
        this.chooseImgList = row.attachList // 让chooseImgList与attachList数据同步
      }
      // 为了让 选中值 图片所选的同步
      if (this.form.id) {
        const foundElement = this.selectionList.find(item => item.id == row.id)
        if (!foundElement) {
          this.$refs.multipleTable?.toggleRowSelection(row)
        }
      }
    },
    // 选择图片确认
    chooseImgOkFun() {
      this.chooseImgList.forEach((e, index) => {
        e.checked = this.imgList[index].checked
      })
      this.imgDialog = false
    },
    /** 查询整改巡检单记录列表 */
    getList() {
      this.loading = true
      listForm(this.queryParams)
        .then((response) => {
          this.formList = response.rows || []
          this.total = response.total || 0
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.showTable = false
      this.form = {
        id: null,
        formPath: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        formTitle: null,
        rectificationDeadline: null,
        delFlag: null,
        formDes: null,
        rectificationRequirements: null,
        rectificationRequirementsList: [], // 整改要求
        projectName: null,
        qualityQuestionId: null, // 关联质量问题id 串,逗号分隔传给后端
        projectId: this.$store.state.app.selectData,
        itemList: []// 选择的质量问题台账和选中的图片
      }
      this.selectionList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加整改巡检单记录'
      this.queryParamsDialog.pageNum = 1
      this.queryParamsDialog.projectId = this.$store.state.app.selectData
      this.showTable = true
      this.getQualityProblemList()
      // 获取最后一条记录的【整改期限和检查描述】
      this.getLastOneFun()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      this.newItemList = []
      this.title = '修改整改巡检单记录'
      const id = row.id
      this.showTable = true
      this.formLoading = true
      getForm(id).then((response) => {
        this.formLoading = false
        this.form = response.data || this.form
        let arr = []
        if (this.form.rectificationRequirementsList?.length) {
          this.form.rectificationRequirementsList.forEach(e => {
            arr.push(e.itemDes)
          })
        } else {
          arr = []
        }
        this.form.rectificationRequirementsList = arr
        this.form.itemList = this.form.itemList || []
        this.newItemList = JSON.parse(JSON.stringify(this.form.itemList))
        this.queryParamsDialog.pageNum = 1
        this.queryParamsDialog.projectId = this.form.projectId
        // 根据返回的数据，进行列表选中页面回显
        this.getQualityProblemList()
      }).catch(() => {
        this.formLoading = false
      })
    },
    // 根据返回的数据，进行列表选中页面回显
    getData() {
      this.list.forEach(e => {
        this.newItemList.forEach(item => {
          if (item.qualityQuestionsId == e.id) {
            this.$refs.multipleTable?.toggleRowSelection(e)
            const imgName = []
            if (item.pidIdsList?.length) {
              item.pidIdsList.forEach(img => {
                imgName.push(img.name)
              })
            }
            if (e.attachList?.length) {
              e.attachList.forEach(li => {
                this.$set(li, 'checked', false)
                if (imgName.includes(li.name)) {
                  li.checked = true
                }
              })
            }
          }
        })
      })
    },
    // 获取最后一条记录的【整改期限和检查描述】
    async getLastOneFun() {
      const res = await getLastOne()
      this.form.rectificationDeadline = res.data?.rectificationDeadline
      this.form.formDes = res.data?.formDes
    },
    // 点击分页
    async paginationFun() {
      console.log('走这')
      await this.getQualityProblemList()
    },
    // 获取质量问题台账
    async getQualityProblemList() {
      this.formLoading = true
      // this.selectionList = []
      const res = await getDataList(this.queryParamsDialog)
      this.list = res.rows || []
      this.totalDialog = res.total || 0
      this.formLoading = false
      this.list.forEach(e => {
        // 给图片默认添加checked：true属性
        e.attachList.forEach(item => {
          this.$set(item, 'checked', true)
        })
      })
      if (this.form.id) {
        this.getData()
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          if (!this.selectionList?.length) {
            this.$modal.msgError('请至少选择一条巡检单')
            return
          }
          // 对this.selectionList进行数组去重
          if (this.form.id) {
            const map = new Map()
            for (const item of this.selectionList.reverse()) {
              if (!map.has(item.id)) {
                map.set(item.id, item)
              }
            }
            this.selectionList = [...map.values()]
          }
          var qualityQuestionId = []
          this.form.itemList = []
          this.selectionList.forEach(e => {
            qualityQuestionId.push(e.id)
            const imgList = []
            e.attachList.forEach(i => {
              if (i.checked) {
                imgList.push({ bucket: i.bucket, name: i.name })
              }
            })
            this.form.itemList.push({ qualityQuestionsId: e.id, questionInfo: e.questionDesc, pidIdsList: imgList })
          })
          // 修改
          if (this.form.id) {
            const arrIds = []
            this.newItemList.forEach(e => {
              const foundElement = qualityQuestionId.find(item => item == e.qualityQuestionsId)

              if (!foundElement) {
                this.form.itemList.push(e)
                arrIds.push(e.qualityQuestionsId)
              }
            })
            qualityQuestionId = qualityQuestionId.concat(arrIds)
          }

          this.form.qualityQuestionId = qualityQuestionId.join()

          var txtList = []
          if (this.form.rectificationRequirementsList?.length) {
            this.form.rectificationRequirementsList.forEach((e, index) => {
              txtList.push({ itemDes: e, itemOrder: index + 1 })
            })
          }
          const currentDate = new Date()
          const year = currentDate.getFullYear()
          const month = currentDate.getMonth() + 1 // 月份是从0开始的，所以加一
          const day = currentDate.getDate()
          let pathName = ''
          if (this.form.id != null) {
            pathName = 'quality/form/editInfo'
          } else {
            pathName = 'quality/form'
          }
          await download1(
            pathName,
            { ...this.form, rectificationRequirementsList: txtList },
            `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}整改通知单.docx`
          )

          // if (res) {
          this.open = false
          this.getList()
          this.reset()
          // }

          // addForm(this.form).then((response) => {
          //   this.$modal.msgSuccess('新增成功')
          //   this.open = false
          //   this.getList()
          // }).catch(() => {
          //   this.$modal.msgError('新增失败')
          // })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除整改巡检单记录编号为"' + ids + '"的数据项？')
        .then(function() {
          return delForm(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport(id) {
      const currentDate = new Date()
      const year = currentDate.getFullYear()
      const month = currentDate.getMonth() + 1 // 月份是从0开始的，所以加一
      const day = currentDate.getDate()
      download1(
        'quality/form/exportInfo',
        { id },
        `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}整改通知单.docx`
      )
    }
  }
}
</script>
<style scoped lang="scss">

.previewImg {
  display: flex;
  .img-box {
      width: 148px;
      height: 160px;
      margin-right: 20px;
      margin-bottom: 20px;
      border: 1px solid #ddd;
      display: flex;
      flex-direction: column;
      align-items: center;
    .img {
      width: 100%;
      height: 148px;
      margin-bottom: 10px;
    }
  }
}

.txt-box {
  cursor: pointer;
  white-space: normal;  /* 允许换行 */
  overflow-wrap: break-word;  /* 在必要时单词内部断行 */
}
.txt-box:hover {
  color: #1890ff;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

</style>
